package token;

import java.util.Arrays;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

public class TokenUtilService {

    private RedisTemplate redisTemplate;

    private static final String TOKEN = "token";

    /**
     * 创建token并存入redis
     * @param value
     * @return token
     */
    public String generateToken(String value){
        String token = UUID.randomUUID().toString();
        String key = TOKEN+token;
        redisTemplate.set(key , value , TimeUnit.MINUTES);
        return token;
    }

    public boolean validToken(String token , String value){
        //lua脚本
        String script =
                "if redis.call('get',KEY[1]) == KEY[2] then return redis.call('del',KEY[1]) else return 0 end";
        RedisScript<Long> redisScript = new RedisScript<Long>(script , Long.class);//非真实代码仅供参考
        String key = TOKEN+token;
        //执行lua脚本
        Long result = redisTemplate.execute(redisScript , Arrays.asList(key , value));
        if( result != null && result != 0L ){
            System.out.println("验证token 成功");
            return true;
        }
        System.out.println("验证token 失败");
        return false;
    }
}
